$(function () {
	var sid;
    $("#jqGrid").jqGrid({
        url: baseURL + 'water/taccountmanage/list',
        datatype: "json",
        colModel: [			
			{ label: '小区名称', name: 'proName', index: 'pro_name', width: 150, key: true },
			{ label: '系统类型', name: 'desc14', index: 'desc14', width: 80 },
			{ label: '采集方式', name: 'modeName', index: 'mode_id', width: 80 },
			{ label: '设备数量', name: 'deviceCount', index: 'device_count', width: 80 },
			{ label: '表总数', name: 'scount', index: 's_count', width: 80 },
			{ label: '保洁表数', name: 'cleanCount', index: 'clean_count', width: 80 },
			{ label: '网点表数', name: 'salesCount', index: 'sales_count', width: 80 },
			//{ label: '类型', name: 'proTypeName', index: 'pro_type_id', width: 80 },
			//{ label: '采集方式', name: 'modeName', index: 'mode_id', width: 80 },
			{ label: '是否竣工', name: 'installerPhone', index: 'installer_phone', width: 80,  formatter: function(value, options, row){
					return value === '已竣工' ?
						'<span class="label label-success">已竣工</span>' :
						'<span class="label label-danger">未知</span>';
				} },
			{ label: '项目经理', name: 'debugerName', index: 'debuger_name', width: 80 },
			{ label: '小区说明', name: 'proDesc', index: 'pro_desc', width: 80 },
			{ label: '小区横坐标', name: 'mapX', index: 'map_x', width: 80,hidden:true },
			{ label: '小区纵坐标', name: 'mapY', index: 'map_y', width: 80,hidden:true },
			{ label: '竣工时间', name: 'installerName', index: 'installer_name', width: 80 },
			//{ label: '开工时间', name: 'debugerPhone', index: 'debuger_phone', width: 80 },
			{ label: '管理所', name: 'unitName', index: 'unit_w_id', width: 80 },
			{ label: '区域', name: 'areaName', index: 'area_id', width: 80 },

			//{ label: '所ID', name: 'unitWId', index: 'unit_w_id', width: 80 },
			{ label: '区域ID', name: 'areaId', index: 'area_id', width: 80,hidden:true },

			{ label: '隶属区域ID', name: 'unitGId', index: 'unit_g_id', width: 80,hidden:true },
			{ label: '小区类型', name: 'proTypeId', index: 'pro_type_id', width: 80,hidden:false ,formatter: function(value, options, row){
					return value == '0' ?	'水表' :(value =='1'?'煤气表':(value=='2'?'水表和煤气表':'未知'));
				}},
			{ label: '备注1', name: 'memo1', index: 'memo1', width: 80,hidden:true },
			{ label: '备注2', name: 'memo2', index: 'memo2', width: 80,hidden:true },
			{ label: '备注3', name: 'memo3', index: 'memo3', width: 80,hidden:true },
			{ label: '备注4', name: 'memo4', index: 'memo4', width: 80,hidden:true },
			{ label: '备注5', name: 'memo5', index: 'memo5', width: 80,hidden:true },
			{ label: '备注6', name: 'memo6', index: 'memo6', width: 80,hidden:true },
			{ label: '备注7', name: 'memo7', index: 'memo7', width: 80 ,hidden:true},

			{ label: 'beforedate', name: 'beforedate', index: 'beforedate', width: 80,hidden:true },
			{ label: 'afterdate', name: 'afterdate', index: 'afterdate', width: 80,hidden:true },
			{ label: 'beforedata', name: 'beforedata', index: 'beforedata', width: 80,hidden:true },
			{ label: 'afterdata', name: 'afterdata', index: 'afterdata', width: 80,hidden:true },
			{ label: 'beforetotaldata', name: 'beforetotaldata', index: 'beforetotaldata', width: 80,hidden:true },
			{ label: 'aftertotaldata', name: 'aftertotaldata', index: 'aftertotaldata', width: 80,hidden:true },
			//{ label: '故障数', name: 'faultcount', index: 'faultcount', width: 80 },
			//{ label: '异常数', name: 'abnormal', index: 'abnormal', width: 80 },
			//{ label: '时间', name: 'nowDate', index: 'now_date', width: 150 },
			//{ label: '设备数', name: 'scount', index: 's_count', width: 80 },
			{ label: 'mapWaiwang', name: 'mapWaiwang', index: 'map_waiwang', width: 80,hidden:true },
			{ label: 'updatepardate', name: 'updatepardate', index: 'updateParDate', width: 80,hidden:true }
        ],
		viewrecords: true,
        height: $(window).height() > 385 ?  $(window).height() - 160 : 385,
        rowNum: 55,
		rowList : [10,30,50,100,200],
        rownumbers: true, 
        rownumWidth: 55,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
		ondblClickRow: function(rowid, iRow, iCol, e){
			$("#jqGrid").jqGrid('resetSelection');
			//$("#jqGrid").jqGrid('setSelection',$("#selRow").val(),false);
			$("#jqGrid").jqGrid('setSelection',rowid);
			var rowData = $("#jqGrid").jqGrid("getRowData", rowid);

			vm.openInfoLayer(rowData);

			$('#myTab a:first').tab('show');
		},
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
			$(window).on('resize', function() {
				var $content = $('.content');
				$content.height($(this).height() - 154);
				$content.find('iframe').each(function() {
					$(this).height($content.height());
				});

				//$(window.parent.document).find("#if1").height($("#content").height());

				$("#deptTreeLeft").css({height:($("#content > div.col-md-10").height()-45)+'px'});
			}).resize();
        },
		onSelectRow: function (rowid, status) {
			// 当前选中行，用于页面调用reloadJqGrid刷新后，继续选中之前选中的
			sid = rowid;
		},
//页面调用reloadJqGrid刷新后，继续选中之前选中的
		loadComplete:function () {
			if (sid){
				$(this).jqGrid("setSelection",sid);
			}
		}
    });

	$(function () {
		$('#inputClear').click(function () {
			$('input')[0].value = "";
			vm.q.value="";
		})
	});

	$('#datetimepicker1,#datetimepicker2,#datetimepicker3,#datetimepicker4,#datetimepicker5,#datetimepicker6,#datetimepicker7,#datetimepicker8').datetimepicker({
		format: 'YYYY.MM.DD',
		locale: moment.locale('zh-cn')
	});

	var interval = null;//计时器
	if (hasSaveOrUpdatePermission) {
		new AjaxUpload('#upload', {
			action: baseURL + "water/taccountmanage/importExcel",
			name: 'myfile',
			autoSubmit: true,
			responseType: "json",
			onSubmit: function (file, extension) {
				if (!(extension && /^(xls|xlsx)$/.test(extension.toLowerCase()))) {
					alert('只支持xls和xlsx格式文件！');
					return false;
				}

				event.preventDefault();
				$('#myModal').modal('show');
				vm.currPer = 0;
				if (interval == null) {
					interval = setInterval(function () {
						$.ajax({
							url: baseURL + "progress/list",
							type: 'POST',
							dataType: 'text',
							data: {
								filename: file,
							},
							success: function (responseText) {
								var data = JSON.parse(responseText);
								vm.progressbar = parseInt(data.progress);
								$("#probar").css("width", parseInt(vm.currPer += 10) + "%");
								if (vm.currPer >= 100) vm.currPer = 0;
							},
							error: function () {
								clearInterval(interval);
								interval = null;
							}
						});
					}, 500);
				}
			},
			onComplete: function (file, r) {
				if (r.code == 0) {

					vm.progressbar = 0;
					clearInterval(interval);
					interval = null;
					$('#myModal').modal('hide');

					layer.msg("文件【" + r.url + "】导入完毕！", {icon: 1});

					vm.query();
				} else {
					alert(r.msg);
				}
			}
		});

		//2023.11.21 上传图纸
		var uploadmap = new AjaxUpload('uploadmap',{
			action: baseURL + "water/taccountmanage/importmap",
			data:{
				'deptname' : '',
			},
			name: 'mymap',
			autoSubmit: true,
			responseType: "json",
			onSubmit: function (file, extension) {
				//console.log($("#jqGrid").getGridParam("selrow"));
				if (!(extension && /^(dwg|rar|zip|gzip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx|bmp|jpeg|jpg|png|gif)$/.test(extension.toLowerCase()))) {
					alert('只支持预定格式文件！');
					return false;
				}
				uploadmap.setData({'deptname': $("#jqGrid").getGridParam("selrow")});
			},
			onComplete: function (file, r) {
				if (r.code == 0) {
					layer.msg("文件【" + r.url + "】导入完毕！", {icon: 1});
				} else {
					alert(r.msg);
				}
			}
		});

	}
});

function zTreeOnDblClick(event, treeId, treeNode) {
	vm.q.dept = treeNode.deptId;
	vm.newpage = true;
	vm.reload();

	//console.log(vm.q.dept);

	//alert(treeNode.deptId);
	//alert(treeNode ? treeNode.tId + ", " + treeNode.name : "isRoot");
};

var settingLeft = {
	data: {
		simpleData: {
			enable: true,
			idKey: "deptId",
			pIdKey: "parentId",
			rootPId: -1
		},
		key: {
			url:"nourl"
		}
	},
	callback: {
		onDblClick: zTreeOnDblClick
	}
};

var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			key: '',
			value:null,
			dept:null,
		},

		mappath:'none.png',

		op :'',
		newpage : false,
		searchKeyDictInfo: {},

		//下拉列表内容填充
		modeInfo:{},
		unitInfo:{},
		areaInfo:{},

		meterTypeInfo:{},
		meterBrandInfo:{},
		meterRopeInfo:{},
		meterFixedAddr:{},

		meterSystemModeInfo:{},

		showList: true,
		title: null,
		tAccountManage: {},

		progressbar : 0,
		currPer:0,
	},
	methods: {
		downloadmap: function(){
			var dept = $("#jqGrid").getGridParam("selrow");
			var url = baseURL
				+ "water/taccountmanage/downloadmap?params="
				+ encodeURIComponent(JSON.stringify({key:dept}));

			//console.log(decodeURIComponent(url));
			location.href = url;
		},
		getDeptTreeLeft: function(){
			$.get(baseURL + "water/waterdept/queryCityAreaUnit", function(r){
				//console.log(r);
				ztree = $.fn.zTree.init($("#deptTreeLeft"), settingLeft, r);
				fuzzySearch('deptTreeLeft','#treeSearchKey',null,true);

				var node = ztree.getNodeByParam("deptId", vm.q.dept);
				if(node != null){
					ztree.selectNode(node);
					vm.q.dept = node.deptId;
				}
				var temp=ztree.getNodes();
				getNum(ztree,temp);
			})
		},
		getSearchKeyDict: function(){
			$.get(baseURL + "sys/dict/list",{name:"qkey_accountmanage"}, function(r){
				vm.searchKeyDictInfo = r.page.list;
			});

			$.get(baseURL + "water/tareainfo/list", function(r){
				vm.areaInfo = r.page.list;
			});

			$.get(baseURL + "water/tuniinfow/list",{qareaid:"",limit:100,page:"1"}, function(r){
				vm.unitInfo = r.page.list;
			});

			$.get(baseURL + "water/tmodetype/list",function(r){
				vm.modeInfo = r.page.list;
			});

			//字典
			$.get(baseURL + "sys/dict/list",{name:"dict_device_type"}, function(r){
				vm.meterTypeInfo = r.page.list;
			});

			$.get(baseURL + "sys/dict/list",{name:"dict_brand"}, function(r){
				vm.meterBrandInfo = r.page.list;
			});

			$.get(baseURL + "sys/dict/list",{name:"dict_rope"}, function(r){
				vm.meterRopeInfo = r.page.list;
			});

			$.get(baseURL + "sys/dict/list",{name:"dict_fix_addr"}, function(r){
				vm.meterFixedAddr = r.page.list;
			});

			$.get(baseURL + "sys/dict/list",{name:"dict_system_mode"}, function(r){
				vm.meterSystemModeInfo = r.page.list;
			});
		},
		getSecondInfo:function(value){
			$.get(baseURL + "water/tuniinfow/list",{qareaid:value,limit:100,page:"1"}, function(r){
				vm.unitInfo = r.page.list;
			});
		},
		query: function () {
			if(vm.q.value != null && vm.q.value != ""
				&& (vm.q.key == null || vm.q.key == "")){
				alert('请选择查询条件!');
				return;
			}
			vm.newpage=true;

			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.tAccountManage = {};
			vm.op = 'add';
		},
		update: function (event) {
			var proName = getSelectedRow();
			if(proName == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(proName);
		},
		saveOrUpdate: function (event) {
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                var url = vm.op == 'add' ? "water/taccountmanage/save" : "water/taccountmanage/update";

				vm.tAccountManage.debugerPhone=$("#datetimepicker1").val();
				vm.tAccountManage.installerName=$("#datetimepicker2").val();

                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.tAccountManage),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
							vm.newpage=true;
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }

                    }
                });

				vm.op='';
			});
		},
		del: function (event) {
			var proNames = getSelectedRows();
			if(proNames == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "water/taccountmanage/delete",
                        contentType: "application/json",
                        data: JSON.stringify(proNames),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(proName){
			$.get(baseURL + "water/taccountmanage/info/"+proName, function(r){
                vm.tAccountManage = r.tAccountManage;
				vm.getSecondInfo(vm.tAccountManage.areaId);

				$("#datetimepicker1").datetimepicker('setDate',vm.tAccountManage.debugerPhone);
				$("#datetimepicker2").datetimepicker('setDate',vm.tAccountManage.installerName);

				$("#datetimepicker3").datetimepicker('setDate',vm.tAccountManage.debugerPhone);
				$("#datetimepicker4").datetimepicker('setDate',vm.tAccountManage.installerName);
				$("#datetimepicker5").datetimepicker('setDate',vm.tAccountManage.desc3);
				$("#datetimepicker6").datetimepicker('setDate',vm.tAccountManage.desc4);
				$("#datetimepicker7").datetimepicker('setDate',vm.tAccountManage.desc9);
				$("#datetimepicker8").datetimepicker('setDate',vm.tAccountManage.desc11);
            });
		},
		outxls: function(){
			var total = $("#jqGrid").jqGrid('getGridParam', 'records') + "";
			var dept = vm.q.dept==null ? "" : vm.q.dept+  "";
			var url = baseURL
				+ "water/taccountmanage/export?params="
				+ encodeURIComponent(JSON.stringify({key:vm.q.key,value:vm.q.value,dept:dept,limit:total,page:"1"}));

			//console.log(decodeURIComponent(url));
			location.href = url;
		},
		download: function(){
			var url = baseURL + "water/taccountmanage/downloadtemplate";
			location.href = url;
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');

			if(vm.newpage){page = "1";}
			$("#jqGrid").jqGrid('setGridParam',{
				postData:{'key': vm.q.key,'value':vm.q.value,'dept':vm.q.dept},
				page:page
			}).trigger("reloadGrid");

		},
		calDevCount:function(){
			layer.confirm('确定要重新计算设备数量，表数，保洁表数，网点表数？', {
					btn: ['确定', '取消'] //按钮
				},function () {
					$.ajax({
						type: "POST",
						url: baseURL + "water/taccountmanage/caldevicecount",
						contentType: "application/json",
						//data: JSON.stringify(vm.tAccountManage),
						success: function (r) {
							if (r.code === 0) {
								layer.msg("操作成功", {icon: 1});
								vm.reload();
							} else {
								layer.alert(r.msg);
							}
						}
					});
				}, function () {});
		},
		syncData:function(event){
			var proName = getSelectedRows();

			if(proName == null){
				return ;
			}

			layer.confirm('确定导入无磁表数据到该小区采集数据表？', {
				btn: ['确定', '取消'] //按钮
			},function () {
				$.ajax({
					type: "GET",
					url: baseURL + "water/taccountmanage/syncnmvpdevice",
					contentType: "application/json",
					data:{'proName':JSON.stringify(proName)},
					//data: JSON.stringify(vm.tAccountManage),
					success: function (r) {
						if (r.code === 0) {
							layer.msg("操作成功", {icon: 1});
							vm.reload();
						} else {
							layer.alert(r.msg);
						}
					}
				});
			}, function () {});
		},
		syncDataGX:function(event){
			var proName = getSelectedRows();

			if(proName == null){
				return ;
			}

			layer.confirm('确定导入冠翔表数据到该小区采集数据表？', {
				btn: ['确定', '取消'] //按钮
			},function () {
				$.ajax({
					type: "GET",
					url: baseURL + "water/taccountmanage/syncdevicegx",
					contentType: "application/json",
					data:{'proName':JSON.stringify(proName)},
					//data: JSON.stringify(vm.tAccountManage),
					success: function (r) {
						if (r.code === 0) {
							layer.msg("操作成功", {icon: 1});
							vm.reload();
						} else {
							layer.alert(r.msg);
						}
					}
				});
			}, function () {});
		},
		openInfoLayer: function(event){
			$.get(baseURL + "water/taccountmanage/info/"+event.proName, function(r){
				vm.tAccountManage = r.tAccountManage;
				if (r.tAccountManage.desc20!= null) {
					vm.mappath = r.tAccountManage.desc20.substring(r.tAccountManage.desc20.lastIndexOf('/') + 1);
				}
				else{
					vm.mappath = "none.png";
				}
			});

			$.get(baseURL + "water/tuniinfow/list",{qareaid:"",limit:100,page:"1"}, function(r){
				vm.unitInfo = r.page.list;
			});

			layer.open({
				type: 1,
				//offset: '50px',
				skin: 'layui-layer-molv',
				title: "详细信息处理 【"+event.proName+"】",
				area: ['70%', '80%'],
				shade: 0,
				shadeClose: false,
				content: jQuery("#infoLayer"),
				btn: ['确定', '取消'],
				btn1: function (index) {

					if (!hasSaveOrUpdatePermission) {
						layer.close(index);
						return;
					}

					layer.confirm('确定要保存修改的信息吗？', {
						btn: ['保存','放弃'] //按钮
					}, function(){
						vm.tAccountManage.debugerPhone=$("#datetimepicker3").val();
						vm.tAccountManage.installerName=$("#datetimepicker4").val();
						vm.tAccountManage.desc3=$("#datetimepicker5").val();
						vm.tAccountManage.desc4=$("#datetimepicker6").val();
						vm.tAccountManage.desc9=$("#datetimepicker7").val();
						vm.tAccountManage.desc11=$("#datetimepicker8").val();

					$.ajax({
						type: "POST",
						url: baseURL + "water/taccountmanage/update",
						contentType: "application/json",
						data: JSON.stringify(vm.tAccountManage),
						success: function(r){
							if(r.code === 0){
								layer.msg("保存成功", {icon: 1});
								vm.reload();

								layer.close(index);
							}else{
								layer.alert(r.msg);
							}
						}
					});
					});
				}
			});
		},
	},
	created: function(){
		this.getSearchKeyDict();
		this.getDeptTreeLeft();
	}
});